package com.yk.common.data.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yk.common.core.utils.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;


/**
 * 元对象字段填充控制器
 *
 * @author lmx
 * @date 2023/10/17 9:38
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isEmpty(servletRequestAttributes)) {
            setInsertDate(metaObject);
            return;
        }
        if (LoginHelper.loginInd()) {
            setInsertDate(metaObject);
            return;
        }
        setInsertDate(metaObject);
        Long userId = LoginHelper.getLoginUserId();
        this.strictInsertFill(metaObject, "createdBy", Long.class, userId);
        this.strictUpdateFill(metaObject, "updatedBy", Long.class, userId);
    }

    private void setInsertDate(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdAt", Date.class, new Date());
        this.setFieldValByName("updatedAt", null, metaObject);
        this.strictUpdateFill(metaObject, "updatedAt", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        this.setFieldValByName("updatedAt", null, metaObject);
        this.setFieldValByName("updatedBy", null, metaObject);
        if (ObjectUtil.isEmpty(servletRequestAttributes)) {
            this.strictUpdateFill(metaObject, "updatedAt", Date.class, new Date());
            return;
        }
        if (LoginHelper.loginInd()) {
            this.strictUpdateFill(metaObject, "updatedAt", Date.class, new Date());
            return;
        }
        this.strictUpdateFill(metaObject, "updatedAt", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updatedBy", Long.class, LoginHelper.getLoginUserId());
    }
}